package com.rxmvp.interceptor;

import android.text.TextUtils;

import com.loper7.base.utils.Logger;
import com.rxmvp.http.exception.ErrorType;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 返回参数拦截器
 */
public class ResponseInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        //返回参数 []-> null ,{} -> null
        Response response = chain.proceed(request);

        ResponseBody body = response.body();
        String bodyString = body.string();
        if (bodyString.contains("[]")) {
            bodyString = bodyString.replace("[]", "null");
        }
        if (bodyString.contains("{}")) {
            bodyString = bodyString.replace("{}", "null");
        }
        if (bodyString.contains("\"data\":\"\"")) {
            bodyString = bodyString.replace("\"data\":\"\"", "\"data\":null");
        }
        if (bodyString.contains("[null]")) {
            bodyString = bodyString.replace("[null]", "null");
        }
        if (bodyString.contains("{null}")) {
            bodyString = bodyString.replace("{null}", "null");
        }
        if (bodyString.contains("{\"items\":\"\"}")) {
            bodyString = bodyString.replace("{\"items\":\"\"}", "null");
        }

        Response newResponse;
        if (response.code() != 200)
            //请求失败之后重组设置服务器返回的错误信息
            newResponse = response.newBuilder().message(bodyString).body(ResponseBody.create(MediaType.parse(body.contentType().toString()), bodyString)).build(); //重组
        else
            newResponse = response.newBuilder().body(ResponseBody.create(MediaType.parse(body.contentType().toString()), bodyString)).build(); //重组
        return newResponse;
    }
}
